// 讯飞语音转写前端应用
class AudioTranscriber {
    constructor() {
        this.audioFile = null;
        this.initEventListeners();
    }

    initEventListeners() {
        const fileInput = document.getElementById('audioFile');
        const uploadArea = document.getElementById('uploadArea');
        const transcribeBtn = document.getElementById('transcribeBtn');
        const copyBtn = document.getElementById('copyBtn');
        const clearBtn = document.getElementById('clearBtn');

        // 文件选择
        uploadArea.addEventListener('click', () => fileInput.click());
        fileInput.addEventListener('change', (e) => this.handleFileSelect(e));

        // 拖拽上传
        const uploadContainer = uploadArea.parentElement;
        uploadContainer.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadContainer.classList.add('border-blue-400');
        });

        uploadContainer.addEventListener('dragleave', () => {
            uploadContainer.classList.remove('border-blue-400');
        });

        uploadContainer.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadContainer.classList.remove('border-blue-400');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                this.processFile(files[0]);
            }
        });

        // 按钮事件
        transcribeBtn.addEventListener('click', () => this.startTranscription());
        copyBtn.addEventListener('click', () => this.copyText());
        clearBtn.addEventListener('click', () => this.clearResult());
    }

    handleFileSelect(event) {
        const file = event.target.files[0];
        if (file) {
            this.processFile(file);
        }
    }

    processFile(file) {
        // 验证文件类型
        const allowedTypes = ['audio/wav', 'audio/mp3', 'audio/m4a', 'audio/flac', 'audio/x-wav'];
        const allowedExtensions = ['.wav', '.mp3', '.m4a', '.flac'];

        const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
        
        if (!allowedTypes.includes(file.type) && !allowedExtensions.includes(fileExtension)) {
            alert('请选择支持的音频格式：WAV, MP3, M4A, FLAC');
            return;
        }

        // 验证文件大小（最大50MB）
        const maxSize = 50 * 1024 * 1024; // 50MB
        if (file.size > maxSize) {
            alert('文件大小不能超过50MB');
            return;
        }

        this.audioFile = file;
        this.displayFileInfo(file);
        document.getElementById('transcribeBtn').disabled = false;
    }

    displayFileInfo(file) {
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');

        fileName.textContent = file.name;
        fileSize.textContent = this.formatFileSize(file.size);
        fileInfo.classList.remove('hidden');
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    async startTranscription() {
        if (!this.audioFile) {
            alert('请先选择音频文件');
            return;
        }

        const transcribeBtn = document.getElementById('transcribeBtn');
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const progressText = document.getElementById('progressText');

        // 禁用按钮并显示进度
        transcribeBtn.disabled = true;
        progressContainer.classList.remove('hidden');
        
        try {
            // 步骤1：上传文件
            progressText.textContent = '正在上传音频文件...';
            progressBar.style.width = '30%';

            const formData = new FormData();
            formData.append('audio', this.audioFile);

            const response = await fetch('/api/transcribe', {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 步骤2：处理转写
            progressText.textContent = '正在转写音频...';
            progressBar.style.width = '70%';

            const result = await response.json();
            
            if (result.success) {
                // 步骤3：完成
                progressBar.style.width = '100%';
                progressText.textContent = '转写完成！';
                
                setTimeout(() => {
                    progressContainer.classList.add('hidden');
                    this.displayResult(result.transcript);
                }, 1000);
            } else {
                throw new Error(result.error || '转写失败');
            }

        } catch (error) {
            console.error('转写错误:', error);
            progressContainer.classList.add('hidden');
            alert('转写失败：' + error.message);
        } finally {
            transcribeBtn.disabled = false;
        }
    }

    displayResult(transcript) {
        const resultContainer = document.getElementById('resultContainer');
        const transcriptionResult = document.getElementById('transcriptionResult');
        
        transcriptionResult.textContent = transcript;
        resultContainer.classList.remove('hidden');
        
        // 滚动到结果区域
        resultContainer.scrollIntoView({ behavior: 'smooth' });
    }

    copyText() {
        const transcriptionResult = document.getElementById('transcriptionResult');
        const text = transcriptionResult.textContent;
        
        navigator.clipboard.writeText(text).then(() => {
            // 显示复制成功提示
            const copyBtn = document.getElementById('copyBtn');
            const originalText = copyBtn.innerHTML;
            copyBtn.innerHTML = '<i class="fas fa-check mr-1"></i>已复制';
            copyBtn.classList.add('bg-green-600');
            copyBtn.classList.remove('bg-gray-600');
            
            setTimeout(() => {
                copyBtn.innerHTML = originalText;
                copyBtn.classList.remove('bg-green-600');
                copyBtn.classList.add('bg-gray-600');
            }, 2000);
        }).catch(err => {
            console.error('复制失败:', err);
            alert('复制失败，请手动选择文本复制');
        });
    }

    clearResult() {
        const resultContainer = document.getElementById('resultContainer');
        const transcriptionResult = document.getElementById('transcriptionResult');
        
        transcriptionResult.textContent = '';
        resultContainer.classList.add('hidden');
        
        // 重置文件输入
        document.getElementById('audioFile').value = '';
        document.getElementById('fileInfo').classList.add('hidden');
        document.getElementById('transcribeBtn').disabled = true;
        this.audioFile = null;
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new AudioTranscriber();
});
